package com.dream21th.gateway.fliter;

import com.dream21th.common.enums.RtnEnum;
import com.dream21th.common.exception.WebException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter ,Ordered {

    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        String path = uri.getPath();
        HttpHeaders headers = request.getHeaders();
        String safeLevel = headers.getFirst("safe_level");
        //（dev）测试环境对swagger调用接口开放
        /*if(StringUtils.equals(activeProfile,"dev1") && Objects.isNull(safeLevel)){
            return chain.filter(exchange);
        }*/
        if(StringUtils.equals(path,"/user/login") || StringUtils.equals(path,"/captcha.jpg")){
            return chain.filter(exchange);
        }
        String authorization = headers.getFirst("authorization");
        if (Objects.isNull(authorization)){
            log.info("token 为空");
            if(StringUtils.equals(request.getMethodValue(),"GET")){
                String token = request.getQueryParams().getFirst("authorization");
                if(StringUtils.isEmpty(token)){
                    throw new WebException(RtnEnum.NOT_AUTH);
                }else {
                    ServerHttpRequest request1 = exchange.getRequest().mutate().headers(heads -> {
                        heads.add("authorization", token);
                    }).build();
                    ServerWebExchange build = exchange.mutate().request(request1).build();
                    return chain.filter(build);
                }
            }
            throw new WebException(RtnEnum.NOT_AUTH);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
